import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout/index.vue'
import Login from '@/views/Login.vue'
import Detail from "@/views/Detail.vue"
import ImgDetail from '@/views/ImgDetail.vue'
import ImgAll from '@/views/ImgAll.vue'

import errorPage404 from '@/views/errPage/404.vue'

import tabRouter from './page'

import Store from '../store'

// 路由白名单：不管用户是否右权限都可以访问
const whiteList = [
  "Detail",
  '404',
  'Login',
  'Home',
  "ImgDetail",
  "Imgall"
]

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Layout,
    children: tabRouter
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/404',
    name: '404',
    component: errorPage404
  },
  {
    path: '/detail',
    name: 'Detail',
    component: Detail,
    befoerEnter: (to, from, next) => {
      // 特殊的权限判断
      next()
    }
  },
  {
    path: '/imgDetail',
    name: "ImgDetail",
    component: ImgDetail
  },
  {
    path: '/imgall',
    name: "Imgall",
    component: ImgAll
  }
]


const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 全局守卫
router.beforeEach((to, from, next) => {
  // 如果vuex中 过滤好的路由有数据 就是使用过滤好的路由  否则 就使用page的路由
  const showRouter = Store.state.routerList.length ? Store.state.routerList : tabRouter;

  // 获取本地登录信息
  const token = localStorage.getItem('token');

  // 判断是否登录
  if (to.path !== '/login' && !token) {
    next('/login');
  } else {
    // 判断是否有权限访问路由
    if (showRouter.some(item => item.path === to.path) || whiteList.some(item => item === to.name)) {
      next()
    } else {
      next('/404')
    }
  }
})


export default router
